Skip to content

chore: restructure config initialization#17

Merged
cadenkoj merged 2 commits into
mainfrom
05-21-chore_restructure_config_initialization
May 21, 2025
Merged

chore: restructure config initialization#17
cadenkoj merged 2 commits into
mainfrom
05-21-chore_restructure_config_initialization

Conversation

@cadenkoj

@cadenkoj cadenkoj commented May 21, 2025

Copy link
Copy Markdown
Owner

TL;DR

Restructured configuration system with top-level and additional fields.

What changed?

  • Renamed config.rs to settings.rs
  • Added a .gitignore file in the config directory to exclude mesh.toml from version control
  • Implemented a configuration system using the config crate that loads settings from a TOML file and environment variables
  • Defined structured configuration for various components:
    • TLS settings with certificate paths and rotation policy
    • Storage configuration for database and encrypted logs
    • Network settings for peer discovery and gossip protocol
    • Privacy controls
    • Watcher configurations for various security tools (UFW, fail2ban, Suricata, etc.)

How to test?

  1. Create a config/mesh.toml file with appropriate configuration values
  2. Verify the application loads the configuration correctly
  3. Test overriding settings using environment variables with the DTIM_ prefix

Why make this change?

This change establishes an improved structure for the configuration system that allows for flexible configuration of independant nodes in the mesh network through files and environment variables. It provides a centralized way to manage all application settings while supporting different deployment environments. The configuration structure also documents the expected settings for the application.

Summary by CodeRabbit

  • New Features
    • Enhanced configuration management with improved TLS, network, and logging settings.
    • Added cryptographic identity and signature support for network peers.
  • Chores
    • Updated ignore rules to exclude sensitive environment and mesh configuration files.

@coderabbitai

coderabbitai Bot commented May 21, 2025

Copy link
Copy Markdown

Walkthrough

A new .gitignore entry was added to exclude mesh.toml in the config directory and .env in the root from version control. The configuration system was refactored: configuration structs were renamed and reorganized, with a new Settings struct wrapping all config data under a default key. Configuration loading now reads from "config/mesh" and environment variables with prefix "DTIM". The NodePeer struct was expanded with cryptographic fields and methods, and main application code was updated to use these new structures and load settings accordingly.

Changes

File(s) Change Summary
config/.gitignore, .gitignore Added entries to ignore mesh.toml in config/ and .env in the root directory to prevent tracking sensitive or environment-specific files.
config/default.toml Restructured configuration file to nest all settings under [default], renamed keys for TLS and network peers, added new top-level keys address, port, log_level, removed virustotal_api_key, and added apache_error_log.
src/settings.rs Renamed and adjusted configuration structs (SecurityConfigTLSConfig, ConfigSettings), renamed fields (default_peersinit_peers), added new fields to Settings, introduced private Root wrapper struct, changed config loading from load to new reading "config/mesh", and applied #[serde(skip_serializing)] to sensitive fields.
src/main.rs Updated to use settings::Settings instead of config::Config, changed function signatures and variable names accordingly, adapted TLS server config construction to new struct fields, enhanced NodePeer creation with public key and signature handling, replaced previous simpler JSON output with signed JSON output of NodePeer.
src/node.rs Modified NodePeer struct to have public fields id, endpoint, added public_key and optional signature fields, removed constructor method, added getter and setter methods for new fields, and implemented PartialEq trait comparing only id. Changed import of PrivacyConfig to settings::PrivacyConfig.

Sequence Diagram(s)

sequenceDiagram
    participant Main as Main Program
    participant Settings as Settings Loader
    participant ConfigFile as Config File ("config/mesh")
    participant EnvVars as Environment Variables (prefix "DTIM")
    participant NodePeer as NodePeer Struct

    Main->>Settings: call Settings::new()
    Settings->>ConfigFile: Load config file
    Settings->>EnvVars: Load environment variables
    Settings->>Settings: Merge and deserialize into Root → Settings
    Settings-->>Main: Return Settings instance

    Main->>NodePeer: Construct with id, endpoint, public_key
    Main->>NodePeer: Sign serialized NodePeer JSON
    NodePeer->>NodePeer: Set signature field
    Main->>Main: Output signed NodePeer JSON
Loading

Poem

🐇 Hopping through configs, neat and new,
Mesh.toml hides, out of view.
Settings wrapped in a default nest,
TLS keys renamed, all for the best.
Peers now signed with keys so bright,
Our network shines in cryptographic light! ✨🔐

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Owner Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@cadenkoj cadenkoj marked this pull request as ready for review May 21, 2025 21:34
@cadenkoj cadenkoj added the enhancement New feature or request label May 21, 2025 — with Graphite App

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/settings.rs (5)

31-36: Consider using an enum for the privacy level.

The level field is defined as a string, which allows any arbitrary value. Using an enum would provide type safety and restrict inputs to valid privacy levels.

+ use serde::Deserialize;
+ 
+ #[derive(Debug, Deserialize, PartialEq)]
+ #[serde(rename_all = "lowercase")]
+ pub enum PrivacyLevel {
+     Low,
+     Medium,
+     High,
+     Maximum,
+ }

#[derive(Debug, Deserialize)]
#[allow(unused)]
pub struct PrivacyConfig {
-   pub level: String,
+   pub level: PrivacyLevel,
    pub allow_custom_fields: bool,
}

74-77: Consider making the configuration file path configurable.

The configuration file path is currently hardcoded as "config/mesh". Consider making this configurable through an environment variable to support different deployment scenarios.

impl Settings {
    pub(crate) fn new() -> Result<Settings, config::ConfigError> {
+       // Allow overriding the config file path with environment variable
+       let config_path = std::env::var("DTIM_CONFIG_PATH").unwrap_or_else(|_| "config/mesh".to_string());
+
        let config = config::Config::builder()
-           .add_source(config::File::with_name("config/mesh"))
+           .add_source(config::File::with_name(&config_path))
            .add_source(config::Environment::with_prefix("DTIM"))
            .build()?;

7-7: Remove #[allow(unused)] attributes when fields are actually used.

The #[allow(unused)] attributes are used throughout the file. While they might be useful during development, they should be removed for fields that are actually used in the code. Otherwise, they might mask potential issues if some fields become genuinely unused.

Also applies to: 16-16, 23-23, 32-32, 39-39, 54-54, 67-67


55-64: Consider adding validation for configuration values.

The settings struct doesn't validate that the loaded configuration values are within acceptable ranges or formats. Consider implementing a validation method to check values like port ranges, valid IP addresses, etc.

impl Settings {
    // Add a validate method to check configuration values
    pub fn validate(&self) -> Result<(), String> {
        // Validate port is in reasonable range
        if self.port == 0 || self.port > 65535 {
            return Err(format!("Invalid port: {}", self.port));
        }
        
        // Validate log level is one of the accepted values
        match self.log_level.to_lowercase().as_str() {
            "debug" | "info" | "warn" | "error" => {}
            _ => return Err(format!("Invalid log level: {}", self.log_level)),
        }
        
        // Add more validation for other fields
        
        Ok(())
    }
}

Then update the new method to call validation:

pub(crate) fn new() -> Result<Settings, config::ConfigError> {
    // ... existing code ...
    
    let settings = root.default;
+   if let Err(e) = settings.validate() {
+       return Err(config::ConfigError::Message(e));
+   }
    Ok(settings)
}

1-84: Consider adding unit tests for configuration loading.

Since the configuration is critical for the application, it would be beneficial to add unit tests to ensure it loads correctly from files and environment variables.

You could add tests that:

  1. Verify loading from a test configuration file
  2. Check that environment variables override file settings
  3. Ensure errors are properly handled for invalid configurations
  4. Validate the validation logic works correctly

This would help ensure the configuration system remains robust as the application evolves.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between d885b04 and 09b66aa.

📒 Files selected for processing (2)
  • config/.gitignore (1 hunks)
  • src/settings.rs (1 hunks)
🔇 Additional comments (2)
config/.gitignore (1)

1-1: Good practice to exclude configuration files from version control.

Excluding mesh.toml from version control is a good practice as it prevents sensitive configuration data (like API keys and database credentials) from being committed to the repository. This aligns well with the PR's objective to support independent node configuration.

src/settings.rs (1)

6-13: TLS configuration structure looks appropriate for certificate management.

The structure covers key rotation policy and certificate paths, which is good for TLS setup. The Option<PathBuf> for CA is a nice touch to make it optional.

Comment thread src/settings.rs
Comment thread src/settings.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/node.rs (1)

163-166: Consider implementing Eq alongside PartialEq.

The PartialEq implementation correctly identifies peers by their ID only, which is appropriate for identity comparison. However, when implementing PartialEq, it's a best practice to also implement Eq for types where equality is reflexive, symmetric, and transitive.

impl PartialEq for NodePeer {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}
+
+impl Eq for NodePeer {}
src/main.rs (1)

97-97: Consider making the endpoint configurable.

The endpoint is hardcoded as "127.0.0.1:3030", which might limit flexibility in different deployment scenarios.

let mut data = NodePeer {
    id: id.to_string(),
-   endpoint: "127.0.0.1:3030".to_string(),
+   endpoint: format!("{}:{}", settings.network.host.unwrap_or_else(|| "127.0.0.1".to_string()), settings.network.port.unwrap_or(3030)),
    public_key: base64_pubkey,
    signature: None,
};

This assumes that the settings structure has network.host and network.port fields, which may need to be adjusted based on the actual settings structure.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 09b66aa and c0ae9a8.

📒 Files selected for processing (5)
  • .gitignore (1 hunks)
  • config/default.toml (1 hunks)
  • src/main.rs (7 hunks)
  • src/node.rs (2 hunks)
  • src/settings.rs (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • .gitignore
  • config/default.toml
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/settings.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test-lint
🔇 Additional comments (12)
src/node.rs (3)

2-2: Import path updated correctly to match module renaming.

The import path change from config::PrivacyConfig to settings::PrivacyConfig correctly aligns with the PR's configuration restructuring.


135-139: NodePeer struct enhanced with cryptographic identity fields.

The NodePeer struct has been appropriately expanded to include cryptographic identity with the addition of public_key and signature fields. Making the fields public is necessary for the direct struct initialization in main.rs.


150-160: Well-designed accessor methods for the new fields.

The getter and setter methods for the new cryptographic fields follow good encapsulation practices. The get_signature() method correctly handles the optional nature of the signature field.

src/main.rs (9)

7-7: Module name changed to match configuration restructuring.

The module name change from config to settings correctly aligns with the PR's objective of restructuring the configuration system.


23-25: Import statements updated appropriately.

The import statements have been correctly updated to use the new Settings struct, and FromStr was added to support the log level parsing from string configuration values.


47-49: Function signature updated to use new Settings struct.

The server configuration function now correctly accepts a reference to the new Settings struct, and the TLS configuration is accessed through settings.tls instead of the old path.


61-62: Updated path references for TLS certificates and keys.

The code now correctly references the TLS certificate and key paths from the new settings structure.


77-81: Settings initialization and key manager configuration.

The code correctly initializes the new Settings struct and passes it to the key manager and TLS configuration.


93-100: NodePeer construction with cryptographic identity.

The code correctly constructs a NodePeer with the base64-encoded public key and initializes the signature field to None.


110-114: Properly signing the node peer data.

The code correctly signs the serialized JSON bytes and sets the signature on the NodePeer object.


115-115: Output format changed to include full NodePeer with signature.

The output now correctly includes the entire signed NodePeer JSON object, which is more consistent and contains all necessary information.


137-137: Peer initialization field name change.

The code now correctly uses settings.network.init_peers instead of the old field name, which aligns with the configuration restructuring.

Comment thread src/main.rs
Comment on lines +83 to 86
settings.storage.encrypted_logs_path.clone(),
key_mgr.clone(),
LevelFilter::Debug,
LevelFilter::from_str(&settings.log_level).unwrap(),
)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle potential log level parsing failure.

The code uses unwrap() on the log level parsing, which could cause a panic if the configuration contains an invalid log level string.

let logger = logging::EncryptedLogger::new(
    settings.storage.encrypted_logs_path.clone(),
    key_mgr.clone(),
-   LevelFilter::from_str(&settings.log_level).unwrap(),
+   LevelFilter::from_str(&settings.log_level).unwrap_or_else(|_| {
+       log::warn!("Invalid log level: {}, defaulting to Info", settings.log_level);
+       LevelFilter::Info
+   }),
)?;
🤖 Prompt for AI Agents
In src/main.rs around lines 83 to 86, the code uses unwrap() on the log level
parsing which can cause a panic if the log level string is invalid. Replace
unwrap() with proper error handling by matching or using a method like expect
with a clear error message, or returning a Result with an error if parsing
fails. This will prevent the program from panicking on invalid log level
configurations.

@cadenkoj cadenkoj merged commit 9175770 into main May 21, 2025
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant